<template>
  <div class="data-table-container layout-padding">
    <el-card class="layout-padding-auto" shadow="hover">
      <el-form ref="queryFormRef" :model="state.tableData.param.params" inline>
        <el-form-item class="!mr-4" prop="stockTypeId" style="width: 11%">
          <el-select v-model="state.tableData.param.params.stockTypeId"
                     clearable
                     placeholder="请选择操作仓库"
                     size="default">
            <el-option
                v-for="item in state.stockTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="!mr-4" prop="stockStatus" style="width: 11%">
          <el-select v-model="state.tableData.param.params.stockStatus"
                     clearable
                     placeholder="请选择库存状态"
                     size="default">
            <el-option
                v-for="item in state.stockStatusList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-auth="'user.list'" class="!mr-4">
          <el-button size="default" type="primary" @click="getTableData">
            <el-icon>
              <ele-Search/>
            </el-icon>
            查询
          </el-button>
        </el-form-item>
        <el-form-item v-auth="'user.list'" class="!mr-4">
          <el-button size="default" type="primary" @click="onHandleResetFields">
            <el-icon>
              <ele-Refresh/>
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>


      <el-table v-loading="state.tableData.loading" :data="state.tableData.data" highlight-current-row
                style="width: 100%"
                @sort-change="handleSortChange">
        <el-table-column label="ID" prop="id" show-overflow-tooltip/>
        <el-table-column label="库名称" prop="stockTypeName" show-overflow-tooltip/>
        <el-table-column label="商品名称" prop="commodityName" show-overflow-tooltip/>
        <el-table-column label="库存数量" prop="quantity" show-overflow-tooltip>
          <template #default="scope">
            <el-tooltip class="item" content="点击可以调整库存" effect="dark" placement="top">
              <el-link
                  type="primary"
                  @click="openStockChangeDialog(edit,scope.row)"
              >{{ scope.row.quantity }}{{ scope.row.unit }}
              </el-link>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="商品进价" prop="costPrice" show-overflow-tooltip/>
        <el-table-column label="商品售价" prop="salePrice" show-overflow-tooltip>
          <template #default="scope">
            <el-tooltip class="item" content="点击可以调整售价" effect="dark" placement="top">
              <el-link
                  type="primary"
                  @click="handleStockPriceChange(scope.row)">{{ scope.row.salePrice }}
              </el-link>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column align="center" label="毛利额" prop="grossProfit"/>
        <el-table-column align="center" label="毛利率" prop="grossProfitRate">
          <template #default="scope">
            <div v-if="scope.row.grossProfitRate >= 0.2">
              {{ scope.row.grossProfitRate ? (scope.row.grossProfitRate * 100).toFixed(2) : '' }}%
            </div>
            <div v-else style="color: red;">
              {{ scope.row.grossProfitRate ? (scope.row.grossProfitRate * 100).toFixed(2) : '' }}%
            </div>
          </template>
        </el-table-column>
        <el-table-column label="库存状态" prop="stockStatus" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="stock_status" :value="scope.row.stockStatus"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark"/>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button v-if="scope.row.stockStatus === '1'" :disabled="scope.row.loginName === 'admin'" size="small"
                       text
                       type="primary" @click="onRowDel('down',scope.row)">下架
            </el-button>
            <el-button v-else :disabled="scope.row.loginName === 'admin'" size="small" text
                       type="primary" @click="onRowDel('up',scope.row)">上架
            </el-button>

            <el-button :disabled="scope.row.loginName === 'admin'" size="small" text
                       type="primary" @click="onOpenEditUser('info', scope.row)">
              变更记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="state.tableData.param.pageNum"
                     v-model:page-size="state.tableData.param.pageSize" :page-sizes="[10, 20, 30]" :pager-count="5"
                     :total="state.tableData.total" background class="mt15"
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange">
      </el-pagination>
    </el-card>
    <stockDialog ref="stockDialogRef" @refresh="getTableData()"/>
    <upStockDialog ref="upStockdialog" @refresh="getTableData()"/>
  </div>
</template>

<script lang="ts" name="storeStock" setup>
import {defineAsyncComponent, getCurrentInstance, onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {stockApi} from "/@/api/store/stock";
import {dictDataApi} from "/@/api/sys/dictData";
import {stockTypeApi} from "/@/api/store/stock/type";
import DictTag from "/@/components/DictTag/index.vue";

// 引入组件
const stockDialog = defineAsyncComponent(() => import('/src/views/store/stock/dialog.vue'));
const upStockDialog = defineAsyncComponent(() => import('/src/views/store/stock/stockDialog.vue'));

const {proxy} = getCurrentInstance();
const {stock_status} = proxy.useDict("stock_status");

// 定义变量内容
const stockDialogRef = ref();
const upStockdialog = ref();
const queryFormRef = ref();
const state = reactive<SysUserState>({
  tableData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      pageNum: 1,
      pageSize: 10,
      params: {
        stockTypeId: '', // 仓库类型ID
        stockStatus: '', // 库存状态
      },
    }
  },
  stockStatusList: [],
  stockTypeList: [],
});


// 打开变更记录
const onOpenEditUser = (type: string, row: RowUserType) => {
  stockDialogRef.value.openDialog(type, row);
};

const handleSortChange = (data: any) => {
  if (data.order) {
    if (data.order.indexOf('asc') > -1) {
      state.tableData.param.sortOrder = 'asc'
    } else {
      state.tableData.param.sortOrder = 'desc'
    }
    state.tableData.param.sortName = data.prop
  }
  getTableData();
};


// 修改售价
const handleStockPriceChange = (row: any) => {
  let params = JSON.parse(JSON.stringify(row))
  ElMessageBox.prompt(`请修改销售价格？`, '调整商品售价', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputType: 'number',
    inputValue: params.salePrice,
    type: 'warning',
  }).then(({value}) => {
    if (value && value > 0) {
      params.salePrice = value
      stockApi()
          .updateSalePrice(params)
          .then(res => {
            ElMessage.success(res.msg || '调整价格成功');
            getTableData();
          })
          .catch(() => {
            ElMessage.error('操作失败');
          })
    }
  }).catch(() => {
    ElMessage.info('已取消操作');
  })
};

const openStockChangeDialog = (type: string, row: RowUserType) => {
  upStockdialog.value.openDialog(type, row);
}

// 初始化表格数据
const getTableData = () => {
  state.tableData.loading = true;
  stockApi()
      .getTableData(state.tableData.param)
      .then((res) => {
        state.tableData.data = res.data.records;
        state.tableData.total = res.data.total;
        state.tableData.loading = false;
      })
      .catch(() => {
        state.tableData.loading = false;
      });
};
// 删除用户
const onRowDel = (type: String, row: any) => {
  ElMessageBox.confirm(`是否确定执行该操作？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    if (type === 'down') {
      row.stockStatus = 0
    } else {
      row.stockStatus = 1
    }
    stockApi()
        .updateRecord(row)
        .then(() => {
          getTableData();
          ElMessage.success('操作成功');
        });
  }).catch(() => {
    ElMessage.info('操作失败');
  });
};
// 分页改变
const onHandleSizeChange = (val: number) => {
  state.tableData.param.pageSize = val;
  getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
  state.tableData.param.pageNum = val;
  getTableData();
};
// 页面加载时
onMounted(() => {
  getTableData();

  // 库存状态·
  dictDataApi()
      .getDictByType("stock_status")
      .then(res => {
        state.stockStatusList = res.data
      })

  // 仓库数据
  stockTypeApi()
      .findAll()
      .then(res => {
        state.stockTypeList = res.data;
      })
});
// 重置查询表单
const onHandleResetFields = () => {
  queryFormRef.value.resetFields();
  getTableData();
};
</script>
